package org.lzy.shop.util

import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.util.UUID

object FileManager {
    val JPG_SUFFIX = ".jpg"
    // 媒体模块根目录
    private val SAVE_MEDIA_ROOT_DIR = Environment.DIRECTORY_DCIM

    // 媒体模块存储路径
    private val SAVE_MEDIA_DIR: String = "$SAVE_MEDIA_ROOT_DIR/Shop"
    //头像保存路径
    private const val AVATAR_DIR = "/avatar"
    private const val USER_IMAGE = "UserShopImage"

    fun getMediaUri2File(context: Context, fileUri: Uri): File? {
        val  projection=arrayOf(MediaStore.Images.Media.DATA)
        val cursor: Cursor? =context.contentResolver?.query(
            fileUri, projection,
            null, null, null
        )
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                val path = cursor.getString(columnIndex)
                cursor.close()
                return File(path)
            }
        }
        return null
    }


    fun getCacheSize(context: Context): String {
        var cacheSize: Long = 0
        try {
            cacheSize += getFolderSize(context.cacheDir)
            cacheSize += getFolderSize(context.filesDir)

            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                context.externalCacheDir?.let { cacheSize += getFolderSize(it) }
                context.getExternalFilesDir(null)?.let { cacheSize += getFolderSize(it) }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return formatSize(cacheSize)
    }

    private fun getFolderSize(dir: File): Long {
        var size: Long = 0
        if (dir.exists()) {
            if (dir.isDirectory) {
                dir.listFiles()?.forEach { file ->
                    size += getFolderSize(file)
                }
            } else {
                size = dir.length()
            }
        }
        return size
    }

    private fun formatSize(size: Long): String {
        val kb = size / 1024
        val mb = kb / 1024
        val gb = mb / 1024

        return when {
            gb > 0 -> "$gb GB"
            mb > 0 -> "$mb MB"
            kb > 0 -> "$kb KB"
            else -> "$size B"
        }
    }

    fun clearCache(context: Context) {
        // 删除内部缓存
        delDir(context.cacheDir)
        delDir(context.filesDir)

        // 检查外部存储是否可用
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            // 删除外部缓存
            context.externalCacheDir?.let { delDir(it) }
            context.getExternalFilesDir(null)?.let { delDir(it) }
        }
    }

    private fun delDir(dir: File?): Boolean {
        if (dir != null && dir.isDirectory) {
            val children = dir.listFiles()
            children?.forEach { child ->
                val success = delDir(child)
                if (!success) return false
            }
        }
        return dir?.delete() ?: false
    }

    /**
     * 生成文件名
     */
     fun generateFileName(uri: Uri): String {
        val uuid = UUID.randomUUID().toString().replace("-", "")
        val extension = getFileExtension(uri)
        return "${uuid}_image.$extension"
    }

    /**
     * 获取文件扩展名
     */
     fun getFileExtension(uri: Uri): String {
        return when {
            uri.toString().contains(".jpg", ignoreCase = true) -> "jpg"
            uri.toString().contains(".jpeg", ignoreCase = true) -> "jpeg"
            uri.toString().contains(".png", ignoreCase = true) -> "png"
            uri.toString().contains(".webp", ignoreCase = true) -> "webp"
            else -> "jpg" // 默认扩展名
        }
    }

}